<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <title>Title</title>
    <link rel="stylesheet" href="../static/plugins/layui/css/layui.css">
    <link rel="stylesheet" href="../static/plugins/layui/css/formSelects-v4.css">
</head>
<style>
    .ok-body {
        padding: 10px
    }

    .tip {
        margin-left: 120px;
        margin-top: 20px;
        font-size: larger;
    }

    .layui-colla-item span {
        float: right;
        position: relative;
        display: inline-block;
        margin-top: -35px;
        margin-right: 10px;
        opacity: 0;
    }

    .layui-colla-item span:hover {
        opacity: 1;
    }

    .deviceSelect {
        width: 250px;
        height: 35px;
        position: absolute;
        margin-top: -40px;
        margin-left: 35px;
        display: none;
    }

    .partSelect {
        width: 250px;
        height: 35px;
        position: absolute;
        margin-top: -40px;
        margin-left: 35px;
        display: none;
    }
</style>
<body>
<!-- 新增页面时 用于添加部位时的模板 -->
<div id="partCollapseTemplet" class="layui-collapse" lay-filter="collapse" style="display: none;">
    <div class="layui-colla-item">
        <h2 class="layui-colla-title"  name="partName">
            请选择待检查设备
        </h2>
        <div class="layui-form partSelect">
            <div class="layui-inline partSelect-inline">
                <select name="partSelect" lay-verify="required" lay-filter="partSelect" lay-search>
                    <option value=""></option>
                </select>
            </div>
        </div>
        <span>
			<button onclick="editPart(this)" class="layui-btn layui-btn-normal layui-btn-sm"><i
                    class="layui-icon layui-icon-edit"></i></button>
			<button onclick="deletePart(this)" class="layui-btn layui-btn-danger layui-btn-sm"><i
                    class="layui-icon layui-icon-delete"></i></button>
		</span>
        <div class="layui-colla-content">
            <textarea placeholder="当前部位巡检内容" class="layui-textarea"></textarea>
        </div>
    </div>
</div>
<!-- 用于在编辑页面时，来动态添加的部位选择的折叠面板 -->
<div id="partCollaItemTemplet" class="layui-colla-item" style="display: none;">
    <h2 class="layui-colla-title"  name="partName">
        请选择待检查设备
    </h2>

    <div class="layui-form partSelect">
        <div class="layui-inline partSelect-inline">
        </div>
    </div>

    <span>
		<button onclick="editPart(this)" class="layui-btn layui-btn-normal layui-btn-sm"><i
                class="layui-icon layui-icon-edit"></i></button>
		<button onclick="deletePart(this)" class="layui-btn layui-btn-danger layui-btn-sm"><i
                class="layui-icon layui-icon-delete"></i></button>
	</span>

    <div class="layui-colla-content ">
        <textarea placeholder="当前部位巡检内容" class="layui-textarea"></textarea>
    </div>
</div>

<div class="ok-body">
    <blockquote class="layui-elem-quote layui-text">
        巡检计划
    </blockquote>

    <form class="layui-form layui-form-pane" action="">

        <div class="layui-form-item">
            <input type="hidden" name="id" id="id" th:value="${id}">
            <label class="layui-form-label">计划名称</label>
            <div class="layui-input-inline">
                <input type="text" name="name" lay-verify="required" autocomplete="off" class="layui-input">
            </div>
            <div class="layui-form-mid layui-word-aux">必填</div>
        </div>


        <div class="layui-form-item">
            <label class="layui-form-label">描述</label>
            <div class="layui-input-inline">
                <input type="text" name="description" autocomplete="off" class="layui-input">
            </div>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label">设备类型</label>
            <div class="layui-inline">
                <div class="layui-input-inline">
                    <select id="deviceModel" name="deviceModel" lay-verify="required" lay-filter="deviceModel" lay-search>
                        <option value=""></option>
                    </select>
                </div>
            </div>
        </div>


        <div class="layui-form-item">
            <label class="layui-form-label">计划时间</label>
            <div class="layui-input-inline">
                <input type="text" id="planTime" name="planTime" lay-verify="required" placeholder="巡检计划具体时间"
                       autocomplete="off"
                       class="layui-input">
            </div>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label">执行周期</label>
            <div class="layui-inline">
                <div class="layui-input-inline">
                    <select name="cycleType" lay-verify="required" lay-filter="cycle">
                        <option value="1">每天</option>
                        <option value="2">每周</option>
                        <option value="3">每月</option>
                        <option value="4">半年</option>
                        <option value="5">每年</option>
                    </select>
                </div>
            </div>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label">计划执行人</label>
            <div class="layui-input-inline">
                <select name="operatorId" lay-filter="operatorId" lay-search>
                    <option value="">请选择执行人</option>
                </select>
            </div>
        </div>

        <div class="layui-form-item" style="width: 300px;" pane>
            <label class="layui-form-label">状态</label>
            <div class="layui-input-inline">
                <input type="checkbox" checked="" name="status" lay-skin="switch" value="1" lay-filter="switchTest"
                       lay-text="启用|禁用">
            </div>
        </div>

        <div class="layui-form-item">
            <div class="layui-input-block">
                <button class="layui-btn" lay-submit="" lay-filter="submit">立即提交</button>
                <button type="reset" class="layui-btn layui-btn-primary">重置</button>
            </div>
        </div>

    </form>
    <hr/>
    <span style="margin: 10px">
	<button onclick="addDevice()" class="layui-btn  layui-btn-normal"><i
            class="layui-icon layui-icon-add-1"></i> 设备</button>
</span>
    <fieldset class="layui-elem-field site-demo-button" style="margin-top: 10px;">
        <legend>巡检计划内容</legend>

        <div>

            <div class="layui-collapse" id="deviceCollapse" name="deviceCollapse" lay-filter="collapse">
                <div id="deviceCollaItem" class="layui-colla-item">
                    <h2 class="layui-colla-title">
                        请选择待检查设备
                    </h2>

                    <div class="layui-form deviceSelect">
                        <div class="layui-inline">
                            <select name="deviceSelect" lay-verify="required" lay-filter="deviceSelect" lay-search>
                                <option value=""></option>
                            </select>
                        </div>
                    </div>

                    <span>
					<button onclick="editDevice(this)" class="layui-btn layui-btn-normal layui-btn-sm"><i
                            class="layui-icon layui-icon-edit"></i></button>
					<button onclick="deleteDevice(this)" class="layui-btn layui-btn-danger layui-btn-sm"><i
                            class="layui-icon layui-icon-delete"></i></button>
					<button onclick="addPart(this)" class="layui-btn layui-btn-warm layui-btn-sm"><i
                            class="layui-icon layui-icon-add-1"></i></button>
				</span>
                    <div class="layui-colla-content layui-show">
                        <div class="layui-collapse" lay-filter="collapse">

                            <div class="layui-colla-item">
                                <h2 class="layui-colla-title"  name="partName">
                                    请选择检查部位
                                </h2>

                                <div class="layui-form partSelect">
                                    <div class="layui-inline partSelect-inline">
                                        <select name="partSelect" lay-verify="required" lay-filter="partSelect" lay-search>
                                            <option value=""></option>
                                        </select>
                                    </div>
                                </div>

                                <span>
                                <button onclick="editPart(this)" class="layui-btn layui-btn-normal layui-btn-sm"><i
                                        class="layui-icon layui-icon-edit"></i></button>
							    <button onclick="deletePart(this)" class="layui-btn layui-btn-danger layui-btn-sm"><i
                                        class="layui-icon layui-icon-delete"></i></button>
							</span>
                                <div class="layui-colla-content ">
                                    <textarea placeholder="当前部位巡检内容" class="layui-textarea"></textarea>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </fieldset>
</div>


<script src="../static/plugins/layui/layui.js"></script>
<script src="../static/js/jquery-3.2.1.min.js"></script>
<script src="../static/js/jquery.base64.js"></script>
<script src="../static/js/device.js"></script>
<script src="../static/js/collapse-task.js"></script>

<script th:inline="none">
    var element;
    var form;
    var layer;
    layui.use(['element', 'layer', 'jquery', 'form', 'laydate', 'util'], function () {
        element = layui.element;
        layer = layui.layer;
        form = layui.form
        var $ = layui.jquery;
        var util = layui.util;
        var laydate = layui.laydate;
        var tableName = 'cycleTask';
        var id = $('#id').val();
        element.init();
        if (id) {
            //表示是修改页面,名称不能修改
            JJZ.named('name').attr('readonly', 'readonly');

            var param = 'current=1&pageSize=2&searchCol=id&searchValue=' + id;
            JJZ.requestTableData(tableName, param, function (data) {
                var result = data.records[0];
                JJZ.named('name').val(result.name);
                JJZ.named('description').val(result.description);
                //初始化计划时间
                JJZ.named('planTime').val(util.toDateString(result.planTime, 'yyyy-MM-dd HH:mm'));
                result.status == 1 ? '' : JJZ.named('status').removeAttr("checked");

                //初始化计划指令
                var orderList = JSON.parse(result.content);
                //这里初始化巡检计划面板
                initTaskContent(orderList,result.modelId);

                JJZ.named('cycleType').find('option').each(function (index, elem) {
                    $(elem).val() == result.cycleType ? $(elem).attr("selected", "selected") : '';
                });

                //初始化设备类型下拉框
                JJZ.initSelect(JJZ.named('deviceModel'), '/model/dataGrid', function (noError) {
                    if (noError) {
                        JJZ.named('deviceModel').find('option').each(function (index, elem) {
                            $(elem).val() == result.modelId ? $(elem).attr("selected", "selected") : '';
                        });
                        form.render();
                    }
                });

                //初始化计划执行人下拉框
                JJZ.initSelectShowField(JJZ.named('operatorId'), '/user/dataGrid', 'username', function (noError) {
                    if (noError) {
                        JJZ.named('operatorId').find('option').each(function (index, elem) {
                            $(elem).val() == result.operatorId ? $(elem).attr("selected", "selected") : '';
                        });
                        form.render();
                    }
                });
            });

        } else {
            JJZ.initSelectShowField(JJZ.named('operatorId'), '/user/dataGrid', 'username', function (noError) {
                form.render();
            });
            //初始化设备类型下拉框
            JJZ.initSelect(JJZ.named('deviceModel'), '/model/dataGrid', function (noError) {
                form.render();
            });

        }

        //监听折叠
        element.on('collapse(collapse)', function (data) {
            // layer.msg('展开状态：' + data.show);
            $('div.layui-form.deviceSelect').css('display', 'none');
            $('div.layui-form.partSelect').css('display', 'none');
        });

        laydate.render({
            elem: '#planTime',
            type: 'datetime',
            min: 0,
            format: 'yyyy-MM-dd HH:mm'
        });

        form.on('submit(submit)', function (data) {

            var obj = {};
            var cycleType = data.field['cycleType'];
            var cron = initCron(cycleType);
            obj.id = data.field['id'];
            obj.name = data.field['name'];
            obj.description = data.field['description'];
            obj.modelId = data.field['deviceModel'];
            obj.cron = cron;
            obj.cycleType = cycleType;
            obj.planTime = data.field['planTime'];
            obj.status = data.field['status'] == 1 ? 1 : 0;
            obj.operatorId = data.field['operatorId'];
            var content = initCycleTaskContent();
            if(content === 'false'){
                layer.msg('巡检内容有为空的地方，请仔细核对', {icon: 2});
                return false;
            }
            obj.content = content;
            if(id){
                //编辑
                JJZ.editData(tableName, obj, function (data) {
                    window.location.href =JJZ.baseUrl+ '/' + tableName + '/cycleTaskDataGrid';
                });
            }else{
                //新增
                JJZ.addData(tableName, obj, function (data) {
                    window.location.href =JJZ.baseUrl+ '/' + tableName + '/cycleTaskDataGrid';
                });
            }
            return false;
        });

        //监听设备类型下拉框
        form.on('select(deviceModel)',function (data) {

            //清空所有的已经选择了的部位信息
           $('select[name="partSelect"]').empty();

            //第一个设备选择渲染后面的拷贝
            var deviceCollapse = $('div#deviceCollapse');
            $(deviceCollapse).find('h2.layui-colla-title').text('请选择待检查设备');
            $(deviceCollapse).find('h2[name="partName"]').text('请选择检查部位');
            var deviceSelectFirst = $(deviceCollapse).find('select[name="deviceSelect"]:first');
            $(deviceSelectFirst).empty();
            $(deviceSelectFirst).append('<option value=""></option>');
            JJZ.initSelectWithParamAndShow2Field(deviceSelectFirst, '/device/dataGrid', 'current=1&pageSize=99999&searchCol=model_id&searchValue='+data.value,'name','number', function (noError) {
                $(deviceCollapse).find('select[name="deviceSelect"]').each(function (index, element) {
                    if (index != 0) {
                        var cloneSelect = $(deviceSelectFirst).clone(true);
                        var parent = $(element).parent();
                        parent.empty();
                        parent.append(cloneSelect);
                    }
                });
                form.render();
            });
            element.init();
        });


        // 监听设备下拉框,并同步初始化下方的所有部位下拉框
        form.on('select(deviceSelect)', function (data) {
            if (data.value != '') {
                var div = data.othis.parent().parent();
                var h2 = $(div).prev();
                var selectedOption = $(data.elem).find('option:selected');
                $(h2).text(selectedOption.text());
                $(div).css('display', 'none');
                //初始化下面全部的部位下拉框
                var partCollapse = $(div).siblings('div.layui-colla-content');
                //清空之前的数据
                $(partCollapse).find('h2.layui-colla-title').text('请选择检查部位');
                $(partCollapse).find('textarea.layui-textarea').val('');
                //第一个先请求数据库,后面的依次拷贝
                var partSelectFirst = $(partCollapse).find('select[name="partSelect"]:first');
                $(partSelectFirst).empty();
                $(partSelectFirst).append('<option value=""></option>');

                JJZ.initSelect(partSelectFirst, '/devicePart/dataGrid', function (noError) {
                    $(partCollapse).find('select[name="partSelect"]').each(function (index, element) {
                        if (index != 0) {
                            var cloneSelect = $(partSelectFirst).clone(true);
                            var parent = $(element).parent();
                            parent.empty();
                            parent.append(cloneSelect);
                        }
                    });
                    form.render();
                });
                element.init();
            } else {
                var input = data.othis.find('div.layui-select-title').find('input.layui-input.layui-unselect');
                $(input).css('border', 'red solid 1px');
                layer.msg('设备不能为空!');
            }
        });

        // 监听设备部位的下拉框,同步巡检内容到下方内容框
        form.on('select(partSelect)', function (data) {
            if (data.value != '') {
                var div = data.othis.parent().parent();
                var h2 = $(div).prev();
                var selectedOption = $(data.elem).find('option:selected');
                var divContent = $(div).siblings("div.layui-colla-content");
                var textarea = $(divContent).children("textarea.layui-textarea");
                $(h2).text(selectedOption.text());
                $(textarea).val(selectedOption.data().name);
                $(div).css('display', 'none');
                // $(divContent).addClass('layui-show');
                //初始化下面全部的部位下拉框
                element.init();
            } else {
                var input = data.othis.find('div.layui-select-title').find('input.layui-input.layui-unselect');
                $(input).css('border', 'red solid 1px');
                layer.msg('请选择需要检查的部位!');
            }
        });

        function initCron(cycleType) {
            var cron;
            var planTimeStr = JJZ.named('planTime').val();
            //解决ie浏览器不支持 YYYY-MM-dd HH:ss日期格斯 ie支持 YYYY/MM/dd HH:ss
            planTimeStr = planTimeStr.replace(new RegExp(/-/gm),"/");
            var planTime = new Date(planTimeStr);
            if (cycleType == 1) {
                //每天
                cron = String.format('0 {0} {1} * * ?', planTime.getMinutes(), planTime.getHours());
            } else if (cycleType == 2) {
                //每周 0表示星期日
                cron = String.format('0 {0} {1} ? * {2} ', planTime.getMinutes(), planTime.getHours(), planTime.getDay());
            } else if (cycleType == 3) {
                //每月
                cron = String.format('0 {0} {1} {2} * ?', planTime.getMinutes(), planTime.getHours(), planTime.getDate());
            } else if (cycleType == 4) {
                //半年
                var month = planTime.getMonth() + 1;
                if (month > 6) {
                    month = month - 6;
                }
                cron = String.format('0 {0} {1} {2} {3}/6 ?', planTime.getMinutes(), planTime.getHours(), planTime.getDate(), month);
            } else if (cycleType == 5) {
                //一年
                cron = String.format('0 {0} {1} {2} {3} ?', planTime.getMinutes(), planTime.getHours(), planTime.getDate(), planTime.getMonth() + 1);
            }
            return cron;
        }
        //获得编辑完成后的巡检计划内容
        function initCycleTaskContent() {
            var content = [];
            var flag = true;
            $('select[name=deviceSelect]').each(function (index, model) {
                //遍历所有的类型选择框
                var temp = {};
                var selectOption = $(model).find("option:selected");
                if (selectOption.val() == '') {
                    flag = false;
                }
                temp.deviceId = selectOption.val();
                temp.deviceName = selectOption.text();
                var deviceParts = [];
                var partItems = $(model).parent().parent().siblings('div.layui-colla-content').find('div.layui-colla-item');
                $(partItems).each(function (index, part) {
                    //遍历当前类型的部位信息
                    var partInfo = $(part).find('select[name="partSelect"] option:selected');
                    var partTemp = {};
                    if (partInfo.val() == '') {
                        flag = false;
                    }
                    partTemp.partId = partInfo.val();
                    partTemp.partName = partInfo.text();
                    var content = $(part).find('textarea.layui-textarea').val();
                    partTemp.content = content;
                    deviceParts.push(partTemp);
                });
                temp.deviceParts = deviceParts;
                content.push(temp);
            });
            if (flag === false) {
                return 'false';
            }
            return JSON.stringify(content);
        }

    });


    String.prototype.format = function (args) {
        var result = this;
        if (arguments.length > 0) {
            if (arguments.length == 1 && typeof (args) == "object") {
                for (var key in args) {
                    if (args[key] != undefined) {
                        var reg = new RegExp("({" + key + "})", "g");
                        result = result.replace(reg, args[key]);
                    }
                }
            }
            else {
                for (var i = 0; i < arguments.length; i++) {
                    if (arguments[i] != undefined) {
                        //var reg = new RegExp("({[" + i + "]})", "g");//这个在索引大于9时会有问题，谢谢何以笙箫的指出
                        var reg = new RegExp("({)" + i + "(})", "g");
                        result = result.replace(reg, arguments[i]);
                    }
                }
            }
        }
        return result;
    }
    String.format = function () {
        if (arguments.length == 0)
            return null;
        var str = arguments[0];
        for (var i = 1; i < arguments.length; i++) {
            var re = new RegExp('\\{' + (i - 1) + '\\}', 'gm');
            str = str.replace(re, arguments[i]);
        }
        return str;
    }
</script>
</body>
</html>